import {
  Directive,
  ElementRef,
  Renderer,
} from '@angular/core';
import {FormGroupDirective, NgControl, NgForm} from '@angular/forms';

@Directive({
  selector: '[appFloatingInput]',
  host: {
    '(blur)': '_onBlur()',
    '(focus)': '_onFocus()',
    '(input)': '_onInput()',
  }
})
export class FloatingInputDirective {
  /** Whether the element is focused or not. */
  focused = false;

  /** The input element's value. */
  get value() { return this._elementRef.nativeElement.value; }
  set value(value: string) { this._elementRef.nativeElement.value = value; }

  get empty() {
    return this.value == null || this.value === '';
  }

  constructor(private _elementRef: ElementRef,
              private _renderer: Renderer) {
  }

  /** Focuses the input element. */
  focus() { this._renderer.invokeElementMethod(this._elementRef.nativeElement, 'focus'); }

  _onFocus() { this.focused = true; }

  _onBlur() { this.focused = false; }

  _onInput() {
    // This is a noop function and is used to let Angular know whenever the value changes.
    // Angular will run a new change detection each time the `input` event has been dispatched.
    // It's necessary that Angular recognizes the value change, because when floatingLabel
    // is set to false and Angular forms aren't used, the placeholder won't recognize the
    // value changes and will not disappear.
    // Listening to the input event wouldn't be necessary when the input is using the
    // FormsModule or ReactiveFormsModule, because Angular forms also listens to input events.
  }
}
